bind:this

Posted on 2023-02-05 by

henrikvilhelmberglund

If we want to get a reference to a DOM element we can use bind:this . bind:this is a one-way binding .

If we have a variable and assign an element to it using bind:this and try to console.log() immediately it we will get undefined because it is getting defined when Svelte creates the element and mounts it onto the DOM .

To get around this we can use the onMount lifecycle event that is run when the component is mounted onto the DOM .

App.svelte

<script>
	import { onMount } from "svelte";
	let element;
	function reset() {
		element.value = "";
	}
	onMount(() => {
		console.log(element);
	});
</script>

<input bind:this={element} type="text" />

<button on:click={reset}>Reset</button>

        

To be clear, if we don't use the element right away the onMount event isn't necessarily needed. In a simple case this would be enough:

App2.svelte

<script>
	let element;
	function reset() {
		element.value = "";
	}
</script>

<input bind:this={element} type="text" />

<button on:click={reset}>Reset</button>
        

If we use bind:this on a component we get access to its props as well.

App3.svelte

<script>
	let myComponent;
	function logCount() {
		console.log(myComponent.count);
	}
	import Component from "./Component.svelte";
</script>

<Component bind:this={myComponent} />

<button on:click={logCount}>Log Component.svelte's Count</button>

        

Component.svelte

<!-- we also need this to create getters and setters for the component's props -->
<svelte:options accessors />

<script>
	export let count = 0;

	// exporting a function as a prop
	export function reset() {
		count = 0;
	}
	function inc() {
		count++;
	}
</script>

<button on:click={inc}>{count}</button>

        

We do need <svelte:options accessors /> in order to get access to the count variable since it wasn't readonly, but for functions we don't need it.

App4.svelte

<script>
	let myComponent;
	function reset() {
		myComponent.reset();
	}
	import Component2 from "./Component2.svelte";
</script>

<Component2 bind:this={myComponent} />

<button on:click={reset}>Reset Component2.svelte's Count</button>

        

Component2.svelte

<script>
	let count = 0;

	// exporting a function as a prop (or, with bind:this, as a method)
	export function reset() {
		count = 0;
	}
	function inc() {
		count++;
	}
</script>

<button on:click={inc}>{count}</button>

        

This way we can export functions from a component and use it in another component where we bind to it using bind:this so we can use its methods .